package org.example.framework.web;


import org.example.framework.dto.ResponseDTO;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author tangxiao
 */
@RestControllerAdvice
public class GlobalDefaultExceptionHandler {

    /**
     * 参数校验异常
     *
     * @param exception
     * @return ResponseEntity<ResponseDTO>
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseDTO validationException(MethodArgumentNotValidException exception) {
        for (ObjectError e : exception.getAllErrors()) {
            return ResponseDTO.fail(e.getCode(), e.getDefaultMessage());
        }
        return ResponseDTO.fail("400", "未知的参数异常");
    }

    /**
     * 参数校验异常
     *
     * @param exception
     * @return ResponseEntity<ResponseDTO>
     */
    @ExceptionHandler(Exception.class)
    public ResponseDTO validationException(Exception exception) {
        return ResponseDTO.fail("500", exception.getMessage());
    }
}
